package com.scnu.hachimi.manager;

import java.awt.Point;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class MapLoader {
    /**
     * 从.map文件加载地图数据
     * @param filePath 文件路径
     * @return 地图数据，键为地形类型，值为该地形所有点的列表
     * @throws IOException 如果文件读取出现错误
     */
    private static final String[] elements = { "BRICK", "IRON", "GRASS", "RIVER", "base", "BOSS", "elite", "player1", "player2" };
    public static Map<String, List<Point>> getMap(String filePath) throws IOException {
        Map<String, List<Point>> mapData = new HashMap<>();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath, StandardCharsets.UTF_8))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split("=", 2);
                if (parts.length != 2) {
                    continue; // 跳过格式错误的行
                }

                String terrainType = parts[0].trim();
                String coordinates = parts[1].trim();

                List<Point> points = new ArrayList<>();
                String[] pointStrings = coordinates.split(";");
                for (String pointStr : pointStrings) {
                    String[] coords = pointStr.split(",");
                    if (coords.length == 2) {
                        try {
                            int x = Integer.parseInt(coords[0].trim());
                            int y = Integer.parseInt(coords[1].trim());
                            points.add(new Point(x, y));
                        } catch (NumberFormatException e) {
                            // 忽略格式错误的坐标
                            System.err.println("Invalid coordinate format: " + pointStr);
                        }
                    }
                }

                mapData.put(terrainType, points);
            }
            for (String element : elements) {
                // 如果加载的地图包含此元素，则更新列表
                if (!mapData.containsKey(element)) {
                    mapData.put(element, new ArrayList<>());
                }
            }
        }
        return mapData;
    }

//    public static void main(String[] args) {
//        try {
//            Map<String, List<Point>> map = loadMap("text/3.map");
//
//            // 打印结果验证
//            for (Map.Entry<String, List<Point>> entry : map.entrySet()) {
//                System.out.println("Terrain: " + entry.getKey());
//                for (Point p : entry.getValue()) {
//                    System.out.println("  (" + p.x + ", " + p.y + ")");
//                }
//                System.out.println();
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}